package com.hnkywl.sts.dao.organ;

import com.hnkywl.sts.entity.organ.Nbgs;
import com.hnkywl.sts.entity.organ.Qyjg;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.tool.hbm2x.StringUtils;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 说明：
 * 包:        com.hnkywl.sts.dao.sys
 * 类描述:    岗位dao类
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Repository
public class NbgsDao extends SimpleHibernateTemplate<Nbgs, Long> {

    /**
     * 查询内部部门列表
     *
     * @param id       内部部门Id
     * @param mc       内部部门名称
     * @param parentId 上级部门Id
     * @param parentMc 上级部门名称
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Page<Nbgs> findNbgsList(Long id, String mc, Long parentId, String parentMc, int pageNo, int pageSize) {
        Page<Nbgs> page = new Page<Nbgs>(pageNo, pageSize, 0);
        page.setAutoCount(true);
        page.setOrder("asc");
        page.setOrderBy("pxh");
        List<Criterion> criterions = new ArrayList<Criterion>();

        if (YgService.getCurrentYgCxfw() == 2 || YgService.getCurrentYgCxfw() == 3) {
            criterions.add(Restrictions.eq("id", YgService.getCurrentYgGsId()));
        }

        if (id != null) {
            criterions.add(Restrictions.eq("id", parentId));
        } else {
            if (StringUtils.isNotEmpty(mc)) {
                criterions.add(Restrictions.or(Restrictions.like("qc", parentMc, MatchMode.START), Restrictions.like("jc", mc, MatchMode.START)));
            }
        }
        if (parentId != null) {
            criterions.add(Restrictions.eq("sjjg.id", parentId));
        } else {
            if (StringUtils.isNotEmpty(parentMc)) {
                criterions.add(Restrictions.or(Restrictions.like("sjjg.jc", parentMc, MatchMode.START),
                        Restrictions.like("sjjg.qc", parentMc, MatchMode.START)));
            }
        }
        return this.findByCriteria(page, criterions);
    }

    public List<Nbgs> findNbgsList() {
        String hql = "select id as id,qc as qc from Nbgs order by pxh asc";
        return this.getSession().createQuery(hql).setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();
    }

    public List<Nbgs> findNbgs() {
        String hql = " from Nbgs ";
        return (List<Nbgs>) find(hql);
    }

    /**
     * 方法名:     checkUnique
     * 功能描述:   判断参数名称是否重复
     * 输入参数:   @param id 参数的ID propertyName 参数名称
     * 返回值:     @return boolean true表示数据库中已存在，false表示数据库中不存在
     * 异常:      <按照异常名字的字母顺序>
     * 创建人:     scl
     * 创建日期:   13-3-21 下午15:17
     * 修改人:     scl
     * 修改日期:   13-3-21 下午15:17
     */
    public Boolean checkUnique(Long id, Object propertyValue, Object propertyName) {
        String hql;
        if (propertyValue == null)
            return false;
        if (id == null) {
            //修改检验
            hql = "from Nbgs where " + propertyName + " = ? ";
            return this.existsQuery(hql, propertyValue);
        } else {
            //新增检验
            hql = "from Nbgs where " + propertyName + " = ? and id <> ?";
            return this.existsQuery(hql, propertyValue, id);
        }
    }

    /**
     * 获取总公司
     *
     * @return
     */
    public List<Nbgs> findAllRootNbgs() {
        return find("from Nbgs where sjjg = null order by pxh asc, dateCreated desc");
    }

    /**
     * 查找所有内部公司的Id和简称用来生成树内部公司树
     *
     * @return
     */
    public List<Map> findAllNbgs(Long id) {
        SQLQuery sqlQuery = null;
        if (id != null) {
            String sql = "select id as \"id\",jc as \"text\",'icon-tree-nbgs' as \"iconCls\",sjjg_id as \"parentId\" from t_sys_gsjg where sfzx = 0 and type='nbgs' start with id=? connect by prior id=sjjg_id";
            sqlQuery = this.getSession().createSQLQuery(sql);
            sqlQuery.setLong(0, YgService.getCurrentYgZgGsId());
        } else {
            if(YgService.getCurrentYgCxfw()==0){
                String sql = "select id as \"id\",jc as \"text\",'icon-tree-nbgs' as \"iconCls\",sjjg_id as \"parentId\" from t_sys_gsjg where sfzx = 0 and type='nbgs' start with sjjg_id is null connect by prior id=sjjg_id";
                sqlQuery = this.getSession().createSQLQuery(sql);
            }else{
                String sql = "select id as \"id\",jc as \"text\",'icon-tree-nbgs' as \"iconCls\",null as \"parentId\" from t_sys_gsjg where id = ? ";
                sqlQuery = this.getSession().createSQLQuery(sql);
                sqlQuery.setLong(0, YgService.getCurrentYgZgGsId());
            }

        }
        sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
        return sqlQuery.list();
    }

    /**
     * 入库配置查询所有的内部公司
     *
     * @param jc
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Page<Nbgs> findAllNbgs(String jc, int pageNo, int pageSize) {
        String hql = null;
        List<Object> param = new ArrayList<Object>();
        StringBuilder condition = new StringBuilder();
        Page<Nbgs> page = new Page<Nbgs>(pageNo, pageSize, 0);
        //==============条件拼接===============

        if (jc != null && !jc.isEmpty()) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" jc like ? ");
            param.add("%" + jc.trim() + "%");
        }

        //==============记录数量===============
        hql = "select count(*) from Nbgs ";
        if (condition.length() != 0)
            hql = hql + " where " + condition;
        Long c = null;
        if (param.size() != 0) {
            c = (Long) findUnique(hql, param.toArray());
            page.setTotalCount(c.intValue());
        } else {
            c = (Long) findUnique(hql);
            page.setTotalCount(c.intValue());
        }
        if (c == 0)
            return page;
        //==============查询结果===============
        hql = "from Nbgs ";
        if (condition.length() != 0) {
            hql = hql + " where " + condition + "order by dateCreated asc";
        } else {
            hql = hql + "order by dateCreated asc";
        }
        if (param.size() != 0)
            return find(page, hql, param.toArray());
        return find(page, hql);
    }

    public Nbgs findNbgsByQc(String qcName) {
        List<Nbgs> list = find("from Nbgs where qc = ? ", qcName);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

}
